using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using RiceShop.Models;
using RiceShop.Services;
using RiceShop.Extensions;
using System.Net.Http;
using System.Text.Json;
using Microsoft.Extensions.Logging;

namespace RiceShop.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        private readonly IUserService _userService;
        private readonly IConfiguration _configuration;
        private readonly ILogger<UserController> _logger;

        public UserController(IUserService userService, IConfiguration configuration, ILogger<UserController> logger)
        {
            _userService = userService;
            _configuration = configuration;
            _logger = logger;
        }

        /// <summary>
        /// 获取用户列表
        /// </summary>
        /// <param name="search">搜索关键词</param>
        /// <param name="sortBy">排序字段</param>
        /// <param name="ascending">是否升序</param>
        /// <param name="page">页码</param>
        /// <param name="pageSize">每页数量</param>
        /// <returns>用户列表</returns>
        [HttpGet("list")]
        public ActionResult<ApiResponse<IEnumerable<User>>> GetUsers(
            [FromQuery] string? search = null,
            [FromQuery] string sortBy = "Id",
            [FromQuery] bool ascending = true,
            [FromQuery] int page = 1,
            [FromQuery] int pageSize = 10)
        {
            var users = _userService.GetUsers(search ?? "", sortBy, ascending, page, pageSize);
            int totalCount = _userService.GetUsersCount(search ?? "");

            return Ok(ApiResponse<IEnumerable<User>>.Ok(users, "获取用户列表成功", totalCount));
        }

        /// <summary>
        /// 获取用户详情
        /// </summary>
        /// <param name="id">用户ID</param>
        /// <returns>用户详细信息</returns>
        [HttpGet("{id}")]
        public async Task<ActionResult<ApiResponse<User>>> GetUser(long id)
        {
            try
            {
                var user = await _userService.GetUserByIdAsync(id);
                return Ok(ApiResponse<User>.Ok(user, "获取用户信息成功"));
            }
            catch (KeyNotFoundException)
            {
                return NotFound(ApiResponse<User>.Error("用户不存在"));
            }
        }

        /// <summary>
        /// 创建新用户
        /// </summary>
        /// <param name="user">用户信息</param>
        /// <returns>创建的用户信息</returns>
        [HttpPost]
        public async Task<ActionResult<ApiResponse<User>>> CreateUser([FromBody] User user)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var createdUser = await _userService.CreateUserAsync(user);
            return CreatedAtAction(nameof(GetUser), new { id = createdUser.Id },
                ApiResponse<User>.Ok(createdUser, "创建用户成功"));
        }

        /// <summary>
        /// 更新用户信息
        /// </summary>
        /// <param name="id">用户ID</param>
        /// <param name="user">更新的用户信息</param>
        /// <returns>更新结果</returns>
        [HttpPut("{id}")]
        public async Task<ActionResult<ApiResponse<User>>> UpdateUser(long id, [FromBody] User user)
        {
            if (id != user.Id)
            {
                return BadRequest(ApiResponse<User>.Error("用户ID不匹配"));
            }

            try
            {
                var updatedUser = await _userService.UpdateUserAsync(id, user);
                return Ok(ApiResponse<User>.Ok(updatedUser, "更新用户信息成功"));
            }
            catch (KeyNotFoundException)
            {
                return NotFound(ApiResponse<User>.Error("用户不存在"));
            }
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="id">用户ID</param>
        /// <returns>删除结果</returns>
        [HttpDelete("{id}")]
        public async Task<ActionResult<ApiResponse<bool>>> DeleteUser(long id)
        {
            try
            {
                var result = await _userService.DeleteUserAsync(id);
                return Ok(ApiResponse<bool>.Ok(result, "删除用户成功"));
            }
            catch (KeyNotFoundException)
            {
                return NotFound(ApiResponse<bool>.Error("用户不存在"));
            }
        }

        /// <summary>
        /// 更新用户个人资料
        /// </summary>
        /// <param name="userUpdate">更新的用户信息</param>
        /// <returns>更新后的用户信息</returns>
        [HttpPut("profile")]
        [Authorize]
        public async Task<ActionResult<ApiResponse<User>>> UpdateUserProfile([FromBody] User userUpdate)
        {
            var userId = User.GetUserId();
            try
            {
                var updatedUser = await _userService.UpdateUserProfileAsync(userId, userUpdate);
                return Ok(ApiResponse<User>.Ok(updatedUser, "更新用户资料成功"));
            }
            catch (KeyNotFoundException)
            {
                return NotFound(ApiResponse<User>.Error("用户不存在"));
            }
        }

        /// <summary>
        /// 绑定手机号
        /// </summary>
        /// <param name="phoneNumber">手机号码</param>
        /// <returns>绑定结果</returns>
        [HttpPost("bind-phone")]
        [Authorize]
        public async Task<ActionResult<ApiResponse<bool>>> BindPhone([FromBody] string phoneNumber)
        {
            var userId = User.GetUserId();
            try
            {
                var result = await _userService.BindPhoneAsync(userId, phoneNumber);
                return Ok(ApiResponse<bool>.Ok(result, "绑定手机号成功"));
            }
            catch (KeyNotFoundException)
            {
                return NotFound(ApiResponse<bool>.Error("用户不存在"));
            }
        }

        /// <summary>
        /// 微信一键登录
        /// </summary>
        /// <param name="model">微信登录信息</param>
        /// <returns>登录结果，包含用户信息和访问令牌</returns>
        [HttpPost("wxLogin")]
        [AllowAnonymous]
        public async Task<ActionResult<ApiResponse<TokenResult>>> WxLogin([FromBody] WxLoginModel model)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var result = await _userService.WxLogin(model);
            if (result.Success)
            {
                return Ok(result);
            }
            return BadRequest(result);
        }

        /// <summary>
        /// 微信手机号一键登录
        /// </summary>
        /// <param name="model">登录信息，包含code和获取手机号的code</param>
        /// <returns>登录结果，包含用户信息和访问令牌</returns>
        [HttpPost("wxPhoneLogin")]
        [AllowAnonymous]
        public async Task<ActionResult<ApiResponse<TokenResult>>> WxPhoneLogin([FromBody] WxPhoneLoginModel model)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var result = await _userService.WxPhoneLogin(model);
            if (result.Success)
            {
                return Ok(result);
            }
            return BadRequest(result);
        }

        /// <summary>
        /// 获取当前登录用户信息
        /// </summary>
        /// <returns>用户信息</returns>
        [HttpGet("info")]
        [Authorize]
        public async Task<ActionResult<ApiResponse<User>>> GetUserInfo()
        {
            try
            {
                _logger.LogInformation($"开始获取用户信息，Claims: {string.Join(", ", User.Claims.Select(c => $"{c.Type}: {c.Value}"))}");

                var userId = User.GetUserId();
                _logger.LogInformation($"获取到用户ID: {userId}");

                var user = await _userService.GetUserProfileAsync(userId);
                return Ok(ApiResponse<User>.Ok(user, "获取用户信息成功"));
            }
            catch (Exception ex)
            {
                _logger.LogError($"获取用户信息失败: {ex}");
                return BadRequest(ApiResponse<User>.Error($"获取用户信息失败: {ex.Message}"));
            }
        }
    }
}